package models

import "gorm.io/gorm"

type Users struct {
	gorm.Model
	Usersname string `gorm:"type:varchar(50)"json:"usersname"`
	Password  string `gorm:"type:varchar(50)"json:"password"`
}

type Userrolegxbiao struct {
	gorm.Model
	Uid int `gorm:"type:char(11)"json:"uid"`
	Rid int `gorm:"type:char(11)"json:"rid"`
}

type Role struct {
	gorm.Model
	Rolename string `gorm:"type:varchar(50)"json:"rolename"`
}

type Rolenodegxbiao struct {
	gorm.Model
	Rid int `gorm:"type:char(11)"json:"rid"`
	Nid int `gorm:"type:char(11)"json:"nid"`
}

type Node struct {
	gorm.Model
	Nodename string `gorm:"type:varchar(50)"json:"nodename"`
}

type Company struct {
	gorm.Model
	CompanyName string `gorm:"type:varchar(50)"json:"companyName"`
}

type Expect struct {
	gorm.Model
	ExpectName string `gorm:"type:varchar(50)"json:"expectName"`
}

type Orders struct {
	gorm.Model
	Orders string `gorm:"type:varchar(50)"json:"orders"`
	Cid    int    `gorm:"type:char(11)"json:"cid"`
	Eid    int    `gorm:"type:char(11)"json:"eid"`
}

func (*Users) FinData(usersname string, users *Users) error {
	return DB.Where("usersname=?", usersname).First(&users).Error
}

func (*Rolenodegxbiao) AddData(data *Rolenodegxbiao) (int, error) {
	tx := DB.Begin()
	result := DB.Debug().Create(data)
	if result.Error != nil {
		tx.Rollback()
		return 0, result.Error
	}
	tx.Commit()
	return int(data.ID), nil
}

// 角色表-查询用户对应的角色信息
func (*Role) List(uid int) (list []Role, err error) {
	/*
		seleect * form roles
		left join userrolegxbiaos on userrolegxbiaos.rid=roles.id
		where userrolegxbiaos.uid=查询的uid
	*/
	err = DB.Table("roles").
		Joins("left join userrolegxbiaos on userrolegxbiaos.rid=roles.id").
		Where("userrolegxbiaos.uid=?", uid).
		Find(&list).Error
	return list, err
}

// 权限表-角色对应的权限查询
func (*Node) Lists(rid int) (lists []Node, err error) {
	err = DB.Table("nodes").
		Joins("left join rolenodegxbiaos on rolenodegxbiaos.nid=nodes.id").
		Find(&lists).Error
	return lists, err
}

// 物流添加
func (*Company) AddDatas(data *Company) (int, error) {
	tx := DB.Debug()
	result := DB.Debug().Create(data)
	if result.Error != nil {
		tx.Rollback()
		return 0, result.Error
	}
	tx.Commit()
	return int(data.ID), nil
}

func (*Orders) OrdersData(data *Orders) (int, error) {
	tx := DB.Begin()
	result := DB.Debug().Create(data)
	if result.Error != nil {
		tx.Rollback()
		return 0, result.Error
	}
	tx.Commit()
	return int(data.ID), nil
}

func (*Orders) PageList(page int, pageSize int) (list []Orders, err error) {
	offset := (page - 1) * pageSize
	reset := DB.Offset(offset).Limit(pageSize).Find(&list)
	err = reset.Error
	return list, err
}

func (*Orders) OrderDetail(id int) (list Orders, err error) {
	reset := DB.Where("id=?", id).First(&list)
	err = reset.Error
	return list, err
}
